{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## nn.Linear（）详解\n",
    "\n",
    "`PyTorch`的`nn.Linear（）`是用于设置网络中的全连接层的，需要注意在二维图像处理的任务中，全连接层的输入与输出一般都设置为二维张量，形状通常为`[batch_size, size]`，不同于卷积层要求输入输出是四维张量。其用法与形参说明如下：\n",
    "\n",
    "  `in_features`指的是输入的二维张量的大小，即输入的`[batch_size, size]`中的`size`。\n",
    "  `out_features`指的是输出的二维张量的大小，即输出的二维张量的形状为`[batch_size，output_size]`，当然，它也代表了该全连接层的神经元个数。\n",
    "  从输入输出的张量的shape角度来理解，相当于一个输入为`[batch_size, in_features]`的张量变换成了`[batch_size, out_features]`的输出张量。\n",
    "用法示例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([1, 12288])\n",
      "torch.Size([1, 1])\n"
     ]
    }
   ],
   "source": [
    "import torch as t\n",
    "from torch import nn\n",
    "\n",
    "# in_features由输入张量的形状决定，out_features则决定了输出张量的形状 \n",
    "connected_layer = nn.Linear(in_features = 64*64*3, out_features = 1)\n",
    "\n",
    "# 假定输入的图像形状为[64,64,3]\n",
    "input = t.randn(1,64,64,3)\n",
    "\n",
    "# 将四维张量转换为二维张量之后，才能作为全连接层的输入\n",
    "input = input.view(1,64*64*3)\n",
    "print(input.shape)\n",
    "output = connected_layer(input) # 调用全连接层\n",
    "print(output.shape)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[PyTorch的nn.Linear（）详解](https://blog.csdn.net/qq_42079689/article/details/102873766)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "cl",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
